import {
	baseHost
} from '../setting.js'

const errorHandle = () => {
	uni.showToast({
		title: '网络连接错误'
	});

	setTimeout(() => {
		uni.hideToast();
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}, 2000);
}

const request = ({
	path,
	method,
	data = {},
	module,
}) => {
	return new Promise((resolve, reject) => {
		let realBase = ''
		switch (module) {
			case 'recruit':
				realBase = baseHost.recruitHost
				break;
			case 'car':
				realBase = baseHost.car
				break;
			case 'lifeCircle':
				realBase = baseHost.lifeCircleHost
				break;
			case 'shop':
				realBase = baseHost.shop
				break;
		}

		uni.request({
			url: `${realBase}${path}`,
			data,
			header: {
				'guid': uni.getStorageSync('openId'),
			},
			method,
			timeout: 15000,
			success: res => {
				const {
					data,
					statusCode,
				} = res;

				try {
					if (statusCode === 200) {
						if (data.code == '-1') {
							uni.removeStorageSync('token');
							uni.removeStorageSync('shopMsg');
							uni.showModal({
								title: '登录失效，请重新登录！'
							});

							setTimeout(() => {
								uni.hideToast();
								uni.reLaunch({
									url: '/pages/shopmanager'
								})
							}, 2000);

							return;
						}

						// console.log(data.code, 'data.code');

						resolve(res.data);
					} else {
						// console.log(statusCode, 'statusCode');
						errorHandle();
					}

				} catch (e) {
					reject(e);
				}
			},
			fail: err => {
				console.log(err, '请求发生错误');
				
				reject(err);
				uni.showToast({
					title: '网络连接错误'
				});
				
				setTimeout(() => {
					uni.hideToast();
				}, 2000);
			}
		});
	})
}

export default request;
